import globalData, { AppUser } from '@/utils/GlobalData'
import http from '@/utils/HttpClient'

class Account {
  private _initd:boolean = false;
  public async Init () {
    if (this._initd === true) {
      return
    }

    globalData.authSetting = await Megalo.getSetting().then(res => res.authSetting)

    var res = await Megalo.login()
    var data = await http.post({ url: 'weChatAccount/login', data: { code: res.code } })

    if (data.token === null || !globalData.authSetting['scope.userInfo']) {
      Megalo.switchTab({ url: '/pages/account/register' })
      throw new Error('token is empty')
    } else {
      globalData.userInfo = await Megalo.getUserInfo({}).then(res => res.userInfo)
      globalData.appUser = data
    }
    this._initd = true
  }

  public async StartUp () {
    if (globalData.userIsStudent) {
      Megalo.redirectTo({ url: '/student/index' })
    } else if (globalData.userIsTeacher) {
      Megalo.redirectTo({ url: '/teacher/index' })
    } else if (globalData.userIsAdmin) {
      Megalo.redirectTo({ url: '/admin/index' })
    }
  }
}

export default new Account()
